from django.db.models import Q
from django.shortcuts import render
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from proapp.models import *
import jwt
from datetime import datetime, timedelta


# Create your views here.
class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user_obj = User.objects.filter(username=username).first()
        if user_obj.password != password:
            return Response({'msg': '密码不正确'})
        else:
            # Jwt
            payload = {
                'exp': datetime.now() + timedelta(minutes=30),  # 令牌过期时间
                'data': user_obj.id  # 想要传递的信息,如用户名ID
            }
            encoded_jwt = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
            print(encoded_jwt)
            return Response({'msg': '登录成功', 'token': encoded_jwt,'user_id':user_obj.id,'username':user_obj.username})


class CesPro(APIView):
    def post(self, request):
        token = request.data.get('token')
        user_info = jwt.decode(token, settings.SECRET_KEY, algorithm='HS256')
        user_id = user_info.get('data')
        return Response('测试')


import requests
from urllib.parse import urlencode


class WeiBoURL(APIView):
    def post(self, request):
        url = 'https://api.weibo.com/oauth2/authorize?'
        data = {
            'client_id': '794331458',
            'redirect_uri': 'http://127.0.0.1:8000/proapp/callback',
            'response_type': 'code'
        }
        weibo_url = url + urlencode(data)
        return Response({'code': '0', 'msg': '成功', 'data': {'url': weibo_url}})


class WeiBoCallback(APIView):
    def get(self, request):
        code = request.query_params.get('code')
        data = {
            'client_id': '794331458',
            'client_secret': 'cdb0d383472f44061ce13b5e5d1d378b',
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': 'http://127.0.0.1:8000/proapp/callback'
        }
        url = 'https://api.weibo.com/oauth2/access_token'
        weibo_data = requests.post(url=url, data=data)
        data = weibo_data.json()
        access_token = data.get('access_token')  # 获取到的微博token
        weibo_uid = data.get('uid')  # 获取到少码用户的id
        if weibo_uid:
            try:
                user_obj = User.objects.get(username=weibo_uid)
                payload = {
                    'exp': datetime.now() + timedelta(minutes=30),  # 令牌过期时间
                    'data': user_obj.id  # 想要传递的信息,如用户名ID
                }
                encoded_jwt = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
                res_data = {
                    'code': 0,
                    'msg': '授权成功',
                    'data': {
                        'type': '0',
                        'token': encoded_jwt
                    }
                }
                return Response(res_data)
            except Exception as e:
                user_obj = User.objects.create(username=weibo_uid)
                payload = {
                    'exp': datetime.now() + timedelta(minutes=30),  # 令牌过期时间
                    'data': user_obj.id  # 想要传递的信息,如用户名ID
                }
                encoded_jwt = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
                res_data = {
                    'code': 0,
                    'msg': '授权成功,已绑定',
                    'data': {
                        'type': '1',
                        'token': encoded_jwt
                    }
                }
                return Response(res_data)
        else:
            return Response({'code': 999, 'msg': '获取消息失败'})


from utils.MyBaseView import alipay_url
import uuid


class ZfbView(APIView):
    def post(self, request):
        goods_id = request.data.get('goods_id')
        user = request.data.get('username')
        if not all([goods_id, user]):
            return Response({'code': 4005, 'msg': '参数不全'})
        user_obj = User.objects.get(username=user)
        goods_obj = Goods.objects.get(id=goods_id)
        pay_time = datetime.datetime.now()
        order_id = str(uuid.uuid4())
        total_amount = int(goods_obj.price)
        try:

            order_obj = Orders.objects.create(user=user_obj, goods=goods_obj,
                                              order_id=order_id, pay_time=pay_time,
                                              total_amount=total_amount)
            string = '%s 的订单号 %s' % (user_obj.username, order_id)
            url = alipay_url(order_id, total_amount, string)
            return Response({'code': 0, 'msg': 'success', 'data': {'pay_url': url}})
        except Exception as e:
            return Response({'code': 999, 'msg': '失败'})


class GetZfbInfo(APIView):
    def get(self, request):
        print(request.query_params)
        trade_no = request.query_params.get('trade_no')
        order_id = request.query_params.get('out_trade_no')
        order_obj = Orders.objects.get(order_id=order_id)
        order_obj.trade_no = trade_no
        order_obj.status = 2
        order_obj.save()
        return Response({'code': 200, 'msg': 'success'})

class UserView(APIView):
    def get(self,request):
        user_id = request.query_params.get('user_id')
        user_author = User.objects.exclude(id=int(user_id)).values('id','username')
        return Response(user_author)
    def post(self,request):
        user1 = request.data.get('sender')
        user2 = request.data.get('recipent')
        chat_obj = Chat.objects.filter(Q(user1=user1,user2=user2) or Q(user1=user2,user2=user1))
        if chat_obj:
            return Response('聊过，又聊')
        else:
            try:
                chat_name = '%s和%s的聊天' % (user1,user2)
                Chat.objects.create(name=chat_name,user1=user1,user2=user2)
                return Response('正在聊')
            except:
                return Response('聊过')
class ChatView(APIView):
    def get(self,request):
        username = request.query_params.get('username')
        chat_list = Chat.objects.filter(Q(user1=username) or Q(user2=username)).values()
        return Response(chat_list)

class SendView(APIView):
    def post(self,request):
        sender = request.data.get('sender')
        chat_id = request.data.get('chat_id')
        print(chat_id)
        message = request.data.get('message')
        Message.objects.create(message=message,chat_id=int(chat_id),sender=sender)
        return Response('发送成功')

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import time
import json
@accept_websocket
def websocketcontent(request):
    if request.is_websocket():
        while 1:
            time.sleep(1)
            chat_id = request.GET.get('chat_id')
            message_obj = Message.objects.filter(chat_id=int(chat_id)).values('sender','message')
            li = []
            data = {}
            for message in message_obj:
                data["sender"] = message['sender']
                data["message"] = message['message']
                li.append(data)
                print(li,'321')
            request.websocket.send(json.dumps({'data_list':li}))

from rest_framework.viewsets import ModelViewSet
from proapp.ser import *
class BookViewSet(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

class BookView(APIView):
    def post(self,request):
        data = request.data
        book_ser = BookSerializer(data=data)
        book_ser.is_valid()
        book_ser.save()
        return Response('ok')
    def get(self,request):
        book_obj = Book.objects.all().values()
        book_ser = BookSerializer(book_obj,many=True)
        return Response({'msg':book_ser.data})
    def put(self,request):
        data = request.data
        book_ser = BookSerializer(data=data)
        book_ser.is_valid()
        book_ser.save()
        return Response('ok')
    def delete(self,request):
        id = request.query_params.get('id')
        Book.objects.filter(id=int(id)).delete()
        return Response('ok')

